<template>
    <div :class="['mb-2 last:mb-0', depth > 1 ? 'pl-4 border-l border-border' : '']" :ref="setReplyRef">
        <div class="flex gap-2">
            <Link
                :href="route('users.show', reply.user?.username || reply.user?.id)"
                class="flex-shrink-0"
            >
                <img
                    :src="getUserAvatar(reply.user)"
                    :alt="reply.user?.nickname || reply.user?.name"
                    class="w-6 h-6 rounded-full"
                />
            </Link>
            <div class="flex-1 min-w-0">
                <div class="flex items-center justify-between mb-0.5">
                    <div class="flex items-center gap-1.5 flex-wrap">
                        <Link
                            :href="route('users.show', reply.user?.username || reply.user?.id)"
                            class="text-sm font-medium text-foreground hover:underline"
                        >
                            {{ reply.user?.nickname || reply.user?.name }}
                        </Link>
                        <template v-if="reply.parent?.user">
                            <span class="text-sm text-muted-foreground">回复</span>
                            <Link
                                :href="route('users.show', reply.parent.user?.username || reply.parent.user?.id)"
                                class="text-sm text-primary hover:underline font-medium"
                            >
                                {{ reply.parent.user?.nickname || reply.parent.user?.name }}
                            </Link>
                        </template>
                        <span class="text-sm text-muted-foreground">
                            {{ formatTime(reply.created_at) }}
                        </span>
                    </div>
                    <div class="flex items-center gap-2 text-sm text-muted-foreground">
                        <button
                            v-if="page.props.auth?.user"
                            @click="handleReply"
                            class="hover:text-foreground transition-colors"
                        >
                            回复
                        </button>
                        <button
                            v-if="isAuth && !isOwnReply(reply)"
                            @click="$emit('report', reply.id)"
                            class="text-muted-foreground hover:text-foreground transition-colors"
                        >
                            举报
                        </button>
                        <button
                            v-if="isOwnReply(reply)"
                            @click="handleDelete"
                            class="text-red-500 hover:text-red-700 transition-colors"
                        >
                            删除
                        </button>
                    </div>
                </div>
                <p class="text-sm text-foreground whitespace-pre-wrap leading-relaxed">{{ reply.content }}</p>
                
                <!-- 该回复的回复框（动态显示） -->
                <div v-if="replyingTo === reply.id && page.props.auth?.user" class="mt-2 pt-2 border-t">
                    <form @submit.prevent="handleSubmitReply">
                        <textarea
                            :value="replyContent"
                            @input="handleInput"
                            placeholder="回复这条评论..."
                            rows="2"
                            class="w-full px-2 py-1.5 border border-input rounded-md bg-transparent text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 resize-none"
                            required
                            autofocus
                        ></textarea>
                        <div class="flex items-center justify-end gap-2 mt-1.5">
                            <button
                                type="button"
                                @click="handleCancel"
                                class="text-xs text-muted-foreground hover:text-foreground transition-colors px-2 py-1"
                            >
                                取消
                            </button>
                            <button
                                type="submit"
                                :disabled="isSubmitting"
                                class="text-xs text-primary hover:text-primary/80 transition-colors px-2 py-1 disabled:opacity-50"
                            >
                                回复
                            </button>
                        </div>
                    </form>
                </div>
                
                <!-- 递归渲染更深层的嵌套回复（最多3层） -->
                <div v-if="reply.children && reply.children.length > 0 && depth < 3" class="mt-2">
                    <NestedReply
                        v-for="child in reply.children"
                        :key="child.id"
                        :reply="child"
                        :depth="depth + 1"
                        :replying-to="replyingTo"
                        :reply-content="replyContent"
                        :reply-ref="replyRef"
                        @reply="$emit('reply', $event)"
                        @like="$emit('like', $event)"
                        @delete="$emit('delete', $event)"
                        @submit-reply="$emit('submit-reply', $event)"
                        @cancel-reply="$emit('cancel-reply')"
                        @update:reply-content="$emit('update:reply-content', $event)"
                    />
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { Link, usePage } from '@inertiajs/vue3';
import { defineComponent } from 'vue';

export default defineComponent({
    name: 'NestedReply',
    components: {
        Link,
    },
    props: {
        reply: {
            type: Object,
            required: true,
        },
        depth: {
            type: Number,
            default: 1,
        },
        replyingTo: {
            type: Number,
            default: null,
        },
        replyContent: {
            type: String,
            default: '',
        },
        replyRef: {
            type: Function,
            default: null,
        },
    },
    emits: ['reply', 'like', 'delete', 'report', 'submit-reply', 'cancel-reply', 'update:reply-content'],
    setup(props, { emit }) {
        const page = usePage();

        // 设置回复元素的 ref
        const setReplyRef = (el) => {
            if (el && props.replyRef) {
                props.replyRef(props.reply.id, el);
            }
        };

        const getUserAvatar = (user) => {
            if (user?.avatar) {
                return user.avatar.startsWith('http') ? user.avatar : `/storage/${user.avatar}`;
            }
            return `https://api.dicebear.com/7.x/avataaars/svg?seed=${user?.name || 'user'}`;
        };

        const formatTime = (time) => {
            if (!time) return '';
            const date = new Date(time);
            const now = new Date();
            const diff = now - date;
            const minutes = Math.floor(diff / 60000);
            const hours = Math.floor(diff / 3600000);
            const days = Math.floor(diff / 86400000);

            if (minutes < 1) return '刚刚';
            if (minutes < 60) return `${minutes}分钟前`;
            if (hours < 24) return `${hours}小时前`;
            if (days < 7) return `${days}天前`;
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
            });
        };

        const isOwnReply = (reply) => {
            return page.props.auth?.user?.id === reply.user?.id;
        };

        const handleReply = () => {
            emit('reply', props.reply.id);
        };

        const handleDelete = () => {
            emit('delete', props.reply);
        };

        const handleInput = (event) => {
            emit('update:reply-content', event.target.value);
        };

        const handleCancel = () => {
            emit('cancel-reply');
        };

        const handleSubmitReply = () => {
            emit('submit-reply', props.reply.id);
        };

        return {
            page,
            getUserAvatar,
            formatTime,
            isOwnReply,
            handleReply,
            handleDelete,
            handleInput,
            handleCancel,
            handleSubmitReply,
            setReplyRef,
            isSubmitting: false, // 可以从 props 传入或使用全局状态
        };
    },
});
</script>
